<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    width="650"
    placement="right"
    :closable="true"
    @close="close"
    :visible="visible"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;"
  >
    <a-form>
      <a-form-item label="所拥有的权限">
        <a-tree
          checkable
          @check="onCheck"
          :checkedKeys="checkedKeys"
          @expand="onExpand"
          @select="onTreeNodeSelect"
          :selectedKeys="selectedKeys"
          :expandedKeys="expandedKeysss"
          :treeData="treeData"
        >
        </a-tree>
      </a-form-item>
    </a-form>

    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="close" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-drawer>
</template>
<script>
import { queryRolePermission, saveRolePermission } from '@/api/role'
import { permissionMapTree } from '@/api/permission'

export default {
  name: 'UserRoleModal',
  data() {
    return {
      roleId: '',
      treeData: [],
      defaultCheckedKeys: [],
      checkedKeys: [],
      halfCheckedKeys: [],
      expandedKeysss: [],
      allTreeKeys: [],
      autoExpandParent: true,
      checkStrictly: false,
      title: '角色权限配置',
      visible: false,
      loading: false,
      selectedKeys: []
    }
  },
  methods: {
    onTreeNodeSelect(id) {
      if (id && id.length > 0) {
        this.selectedKeys = id
      }
      this.$refs.datarule.show(this.selectedKeys[0], this.roleId)
    },
    onCheck(checkedKeys, { halfCheckedKeys }) {
      // 保存选中的和半选中的，后面保存的时候合并提交
      this.checkedKeys = checkedKeys
      this.halfCheckedKeys = halfCheckedKeys
    },
    show(roleId) {
      this.roleId = roleId
      this.visible = true
    },
    close() {
      this.reset()
      this.$emit('close')
      this.visible = false
    },
    onExpand(expandedKeys) {
      this.expandedKeysss = expandedKeys
      this.autoExpandParent = false
    },
    reset() {
      this.expandedKeysss = []
      this.checkedKeys = []
      this.defaultCheckedKeys = []
      this.loading = false
    },
    handleSubmit() {
      let that = this
      let checkedKeys = [...that.checkedKeys, ...that.halfCheckedKeys]
      const permissionIds = checkedKeys.join(',')
      let params = {
        sysRoleId: that.roleId,
        permissionIds,
        lastPermissionIds: that.defaultCheckedKeys.join(',')
      }
      that.loading = true
      saveRolePermission(params).then(res => {
        if (res.code === 200) {
          that.$message.success('操作成功!')
          that.loading = false
          that.close()
        } else {
          that.$message.error(res.msg || '操作失败!')
          that.loading = false
          that.close()
        }
      })
    },
    convertTreeListToKeyLeafPairs(treeList, keyLeafPair = []) {
      for (const { key, leaf, children } of treeList) {
        keyLeafPair.push({ key, leaf })
        if (children && children.length > 0) {
          this.convertTreeListToKeyLeafPairs(children, keyLeafPair)
        }
      }
      return keyLeafPair
    }
  },
  watch: {
    visible() {
      if (this.visible) {
        permissionMapTree().then(res => {
          let treeList = res.data.treeList
          this.treeData = treeList
          this.allTreeKeys = res.data.ids
          const keyLeafPairs = this.convertTreeListToKeyLeafPairs(this.treeData)
          queryRolePermission({ sysRoleId: this.roleId }).then(res => {
            console.log('打印拥有节点')
            console.log(res.data)
            // 过滤出 leaf node 即可，即选中的
            // Tree组件中checkStrictly默认为false的时候，选中子节点，父节点会自动设置选中或半选中
            // 保存 checkedKeys 以及 halfCheckedKeys 以便于未做任何操作时提交表单数据
            const checkedKeys = [...res.data].filter(key => {
              const keyLeafPair = keyLeafPairs.filter(item => item.key === key)[0]
              return keyLeafPair && keyLeafPair.leaf
            })
            const halfCheckedKeys = [...res.data].filter(key => {
              const keyLeafPair = keyLeafPairs.filter(item => item.key === key)[0]
              return keyLeafPair && !keyLeafPair.leaf
            })
            this.checkedKeys = [...checkedKeys]
            console.log('打印选中节点')
            console.log(this.checkedKeys)
            this.halfCheckedKeys = [...halfCheckedKeys]
            this.defaultCheckedKeys = [...halfCheckedKeys, ...checkedKeys]
            this.expandedKeysss = this.allTreeKeys
          })
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.drawer-bootom-button {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>